package com.ruoyi.service.impl;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.*;
import com.ruoyi.mapper.*;
import com.ruoyi.service.CommanderGradeService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import oshi.driver.mac.net.NetStat;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CommanderGradeServiceImpl implements CommanderGradeService {

    @Autowired
    BasisTaskPlanningMapper basisTaskPlanningMapper;

    @Autowired
    private CommanderGradeMapper commanderGradeMapper;

    @Autowired
    private GradeMapper gradeMapper;

    @Autowired
    private AnswerMapper answerMapper;

    @Autowired
    private ScoreMapper scoreMapper;

    @Autowired
    private ZHUserCaseMapper zhUserCaseMapper;


    @Override
    public R byCaseId(String loadingId) {
        try {
            //先根据 传入的用户获取角色信息
            SysUser sysUser =  SecurityUtils.getLoginUser().getUser();
            List<Long> uids  = new ArrayList<>();
            List<Long> sysUsers = commanderGradeMapper.getByDeptId(sysUser.getDeptId());
            for (Long sysUser1 :sysUsers){
                uids.add(sysUser1);
            }
            if (CollectionUtils.isNotEmpty(uids)){
                List<CommanderGrade > commanderGradeList =  commanderGradeMapper.byCaseId(loadingId,uids);
                for (CommanderGrade commanderGrade:commanderGradeList){
                    String nickName = commanderGradeMapper.getNickName(commanderGrade.getUserId());
                    commanderGrade.setNickName(nickName);
                }
                return R.ok(commanderGradeList);
            }else{
                return R.ok();
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("服务器内部错误");
        }
    }

    @Override
    public R submitTeacher(List<CommanderGrade> commanderGradeList) {
        //通过userid 和caseId 先去查
        //把指挥员的ID 存起来
        SysUser sysUser =  SecurityUtils.getLoginUser().getUser();
        ZHUserCase zhUserCase = new ZHUserCase();
        //怎么获取到 阵地id 呢？
        zhUserCase.setCaseId(commanderGradeList.get(0).getCaseId());
        zhUserCase.setUserId(sysUser.getUserId());
        ZHUserCase zhUserCase2 =  zhUserCaseMapper.selectByuserId(commanderGradeList.get(0).getCaseId(),sysUser.getUserId());
        if (zhUserCase2==null){
            //通过 userId 和 caseId 获取阵地ID
            Long posId = zhUserCaseMapper.getPossitionId(commanderGradeList.get(0).getCaseId(),sysUser.getUserId());
            zhUserCase.setDeptId(posId);
            zhUserCaseMapper.addUserAndloading(zhUserCase);
        }


        //todo status 判端
        List<Long> ids = new ArrayList<>();
        for (CommanderGrade commanderGrade:commanderGradeList){
            ids.add(commanderGrade.getId());
            Grade grade = new Grade();
            Answer answer = answerMapper.getByLoadingIdAndTime(commanderGrade.getCaseId(),commanderGrade.getCapability());
            grade.setId(commanderGrade.getId());
            if (answer!=null){
                int sumScore = 0;
                //都不能为空 答案没有带宽 有调制速率
                //调制速率 调制速率判断
                if(answer.getBandwidth()!=null && commanderGrade.getCarrierPower()!=null){
                    if(upCase(answer.getBandwidth()).equals(upCase(commanderGrade.getCarrierPower()))){
                        grade.setCarrierPowerFlag("10");
                    }else{
                        grade.setCarrierPowerFlag("0");
                    }
                }else{
                    if (answer.getBandwidth()==null && (commanderGrade.getCarrierPower()==null||commanderGrade.getCarrierPower().trim().equals(""))){
                        grade.setCarrierPowerFlag("10");
                    }else{
                        grade.setCarrierPowerFlag("0");
                    }
                }

                //答案带宽是算出来的 学员带宽是输入的 调制速率乘以1.35 就是带宽的答案
                //首先 判断调制速率 的单位 和 带宽的 单位是否一样 不一样 分直接为 零
                //带宽判断
                if(answer.getBandwidth()!=null && commanderGrade.getFrameWidth()!=null){
                    String answerWidth = splitToString(answer.getBandwidth());
                    String gradeWidth = splitToString(commanderGrade.getFrameWidth());
                    if (answerWidth.equals(gradeWidth)){
                        double ans = splitToNumber(answer.getBandwidth())*1.35;
                        double gra = splitToNumber(commanderGrade.getFrameWidth());
                        if (ans==gra){
                            grade.setFrameWidthFlag("10");
                        }else{
                            grade.setFrameWidthFlag("0");
                        }
                    }else{
                            grade.setFrameWidthFlag("0");
                    }
                }

                if(commanderGrade.getFrameWidth()==null){
                    grade.setFrameWidthFlag("0");
                }

                //码率
                //判断 输入 的值  如果 在 答案的区间 1.如果答案是1 输入的不是1 就是错误的  如果答案是0.5 输入的数据 在 0.5+- 0.01 范围内 就是满分  0.429±0.01 范围内就是满分
                if(answer.getCodeRate()!=null && commanderGrade.getCodeRate()!=null){
                    //码率 todo
                    if(answer.getCodeRate().equals("1")){
                        if (commanderGrade.getCodeRate().equals(answer.getCodeRate())){
                            grade.setCodeRateFlag("10");
                        }else{
                            grade.setCodeRateFlag("0");
                        }
                    }
                    if (answer.getCodeRate().equals("0.5")){
                        if (Double.parseDouble(commanderGrade.getCodeRate())<=0.51 && Double.parseDouble(commanderGrade.getCodeRate())>=0.49){
                            grade.setCodeRateFlag("10");
                        }else{
                            grade.setCodeRateFlag("0");
                        }
                    }

                    if(answer.getCodeRate().equals("0.429")){
                        if(Double.parseDouble(commanderGrade.getCodeRate())>=0.419 && Double.parseDouble(commanderGrade.getCodeRate())<=0.439){
                            grade.setCodeRateFlag("10");
                        }else{
                            grade.setCodeRateFlag("0");
                        }
                    }

                    if(answer.getCodeRate().equals("0.312")){
                        if (Double.parseDouble(commanderGrade.getCodeRate())>=0.302 && Double.parseDouble(commanderGrade.getCodeRate())<=0.322){
                            grade.setCodeRateFlag("10");
                        }else{
                            grade.setCodeRateFlag("0");
                        }
                    }
                } else{
                    if (answer.getCodeRate()==null&&commanderGrade.getCodeRate()==null){
                        grade.setCodeRateFlag("10");
                    }else{
                        if(answer.getCodeRate()==null && (commanderGrade.getCodeRate()==null||commanderGrade.getCodeRate().trim().equals(""))){
                            grade.setCodeRateFlag("10");
                        }else{
                            grade.setCodeRateFlag("0");
                        }
                    }
                }

                //调制频点数据
                if (answer.getFrequencyband()!=null){
                    if (answer.getFrequencyband().equals("118-137MHz")){
                        if (commanderGrade.getModulationFrequencyPoint()!=null){
                            Double ansfMax = Double.parseDouble(answer.getFrequency()) +12.5;
                            Double ansfMin = Double.parseDouble(answer.getFrequency()) -12.5;
                            Double point = splitToNumber(commanderGrade.getModulationFrequencyPoint());
                            if (point <=ansfMax && point >=ansfMin){
                                grade.setModulationFrequencyPointFlag("10");
                            }else{
                                grade.setModulationFrequencyPointFlag("0");
                            }
                        }else{
                            grade.setModulationFrequencyPointFlag("0");
                        }
                    }else if(answer.getFrequencyband().equals("225-400MHz")){
                        if (commanderGrade.getModulationFrequencyPoint()!=null){
                            Double ansfMax = Double.parseDouble(answer.getFrequency()) +12.5;
                            Double ansfMin = Double.parseDouble(answer.getFrequency()) -12.5;
                            Double point = splitToNumber(commanderGrade.getModulationFrequencyPoint());
                            if (point <=ansfMax && point >=ansfMin){
                                grade.setModulationFrequencyPointFlag("10");
                            }else{
                                grade.setModulationFrequencyPointFlag("0");
                            }
                        }else{
                            grade.setModulationFrequencyPointFlag("0");
                        }
                    }else if(answer.getFrequencyband().equals("9.75-9.95GHz")){
                        if (commanderGrade.getModulationFrequencyPoint()!=null){
                            Double ansfMax = Double.parseDouble(answer.getFrequency()) +10;
                            Double ansfMin = Double.parseDouble(answer.getFrequency()) -10;
                            Double point = splitToNumber(commanderGrade.getModulationFrequencyPoint());
                            if (point<=ansfMax && point>=ansfMin){
                                grade.setModulationFrequencyPointFlag("10");
                            }else{
                                grade.setModulationFrequencyPointFlag("0");
                            }
                        }else{
                            grade.setModulationFrequencyPointFlag("0");
                        }
                    }else if(answer.getFrequencyband().equals("243-270MHz")){
                        if (commanderGrade.getModulationFrequencyPoint()!=null){
                            Double ansfMax = Double.parseDouble(answer.getFrequency()) +12.5;
                            Double ansfMin = Double.parseDouble(answer.getFrequency()) -12.5;
                            Double point = splitToNumber(commanderGrade.getModulationFrequencyPoint());
                            if (point<=ansfMax && point>=ansfMin){
                                grade.setModulationFrequencyPointFlag("10");
                            }else{
                                grade.setModulationFrequencyPointFlag("0");
                            }
                        }else{
                            grade.setModulationFrequencyPointFlag("0");
                        }
                    }else if(answer.getFrequencyband().equals("1626.5-1660.5MHz")){
                        if (commanderGrade.getModulationFrequencyPoint()!=null){
                            Double ansfMax = Double.parseDouble(answer.getFrequency()) +100;
                            Double ansfMin = Double.parseDouble(answer.getFrequency()) -100;
                            Double point = splitToNumber(commanderGrade.getModulationFrequencyPoint());
                            if (point<=ansfMax && point>=ansfMin){
                                grade.setModulationFrequencyPointFlag("10");
                            }else{
                                grade.setModulationFrequencyPointFlag("0");
                            }
                        }else{
                            grade.setModulationFrequencyPointFlag("0");
                        }
                    }else if(answer.getFrequencyband().equals("10.95-12.75GHz")){
                        if (commanderGrade.getModulationFrequencyPoint()!=null){
                            Double ansfMax = Double.parseDouble(answer.getFrequency()) +10;
                            Double ansfMin = Double.parseDouble(answer.getFrequency()) -10;
                            Double point = splitToNumber(commanderGrade.getModulationFrequencyPoint());
                            if (point<=ansfMax && point>=ansfMin){
                            grade.setModulationFrequencyPointFlag("10");
                            }else{
                                grade.setModulationFrequencyPointFlag("0");
                            }
                        }else{
                                grade.setModulationFrequencyPointFlag("0");
                        }
                    }
                }
                else{
                    if (answer.getFrequencyband()==null && (commanderGrade.getModulationFrequencyPoint()==null||commanderGrade.getModulationFrequencyPoint().trim().equals(""))){
                        grade.setModulationFrequencyPointFlag("10");
                    }else{
                        grade.setModulationFrequencyPointFlag("0");
                    }
                }

                if (answer.getModulationType()!=null && commanderGrade.getModulationType()!=null){
                    //调制方式
                    if(answer.getModulationType().equals(commanderGrade.getModulationType())){
                        grade.setModulationTypeFlag("10");
                    }else{
                        grade.setModulationTypeFlag("0");
                    }
                }else{
                    if (answer.getModulationType()==null && (commanderGrade.getModulationType()==null || commanderGrade.getModulationType().trim().equals(""))){
                        grade.setModulationTypeFlag("10");
                    }else {
                        grade.setModulationTypeFlag("0");
                    }
                }


                if(answer.getChannelCoding()!=null && commanderGrade.getDecodingMethod()!=null){
                    //信道编码 译码方式
                    if(answer.getChannelCoding().equals(commanderGrade.getDecodingMethod())){
                        grade.setChannelCodingFlag("10");
                    }else{
                        grade.setChannelCodingFlag("0");
                    }
                }else{
                    if (answer.getChannelCoding()==null && (commanderGrade.getDecodingMethod()==null||commanderGrade.getDecodingMethod().trim().equals(""))){
                        grade.setChannelCodingFlag("10");
                    }else{
                        grade.setChannelCodingFlag("0");
                    }
                }




                 //调制速率
                if(grade.getCarrierPowerFlag().toString().equals("10")){
                    sumScore = sumScore+10;
                }
                //调制频点数据
                if(grade.getModulationFrequencyPointFlag().toString().equals("10")){
                    sumScore = sumScore+10;
                }
                //调制方式
                if(grade.getModulationTypeFlag().toString().equals("10")){
                    sumScore = sumScore+10;
                }
                //信道编码
                if(grade.getChannelCodingFlag().toString().equals("10")){
                    sumScore = sumScore+10;
                }
                //码率
                if(grade.getCodeRateFlag().toString().equals("10")){
                    sumScore = sumScore+10;
                }
                //带宽
                if(grade.getFrameWidthFlag().toString().equals("10")){
                    sumScore = sumScore+10;
                }
                grade.setSoore(String.valueOf(sumScore));
                gradeMapper.updateGradeScore(grade);
            }
        }
        commanderGradeMapper.updateById(ids);
        return R.ok();
    }

    @Override
    public R getTeacherClass(String loadingId) {
        //通过案例查询阵地
        List<BasisPosition> basisPositions = commanderGradeMapper.getTeacherClass(loadingId);
        return R.ok(basisPositions);
    }

    @Override
    public R getTeacherScoreList(String loadingId, Long positionId) {
        //通过 id 和 案例ID 获取阵营 中的人员
        ScoreVo scoreVo = new ScoreVo();
        List<Long> userIds = commanderGradeMapper.getClassUserid(loadingId,positionId);
        //然后在根据案例ID 和 userId 查询 就可以
        List<CommanderGrade> scores = commanderGradeMapper.byScore(loadingId,userIds);
        Score score = null;
        scoreVo.setCommanderGradeList(scores);
        Integer flag =  scoreMapper.getSc(loadingId,positionId);
        if (flag>0){
             scores = commanderGradeMapper.byScoresum(loadingId,userIds);
             score = scoreMapper.scoreSum(loadingId,positionId);
             scoreVo.setCommanderGradeList(scores);
             scoreVo.setScore(score);
        }
        return R.ok(scoreVo);
    }

    @Override
    public R addScore(Score score) {
       Integer flag =  scoreMapper.getSc(score.getCaseId(),Long.parseLong(score.getPositionId()));
       if(flag<=0){
           scoreMapper.addScore(score);
           return R.ok();
       }else{
          return R.fail("已经评分！");
       }
    }

    @Override
    public R updateStatus(List<CommanderGrade> commanderGrade) {
        List<CommanderGrade> list = new ArrayList<>();
        List<Long> id = new ArrayList<>();
        for (CommanderGrade commanderGrade1:commanderGrade){
            id.add(commanderGrade1.getId());
            commanderGradeMapper.updateByScoreFile(commanderGrade1);
        }
            commanderGradeMapper.updateBidstatus(id);
        return R.ok();
    }

    @Override
    public R getScore(String caseId, Long positionId) {
        return R.ok(scoreMapper.getScore(caseId,positionId));
    }



    @Override
    public R updateDeleteCaseId(String caseId) {
        commanderGradeMapper.updateDeletebaseSignalanalysisInfo(caseId);
        scoreMapper.updateDeleteCaseScore(caseId);
        zhUserCaseMapper.deleteAndLoading(caseId);
        return R.ok();
    }

    @Override
    public R upDateUserStatus(Long userId) {
        commanderGradeMapper.upDateUserStatus(userId);
        return null;
    }



    @Override
    public R getPlan(String caseId, Long deptId) {
        ZHUserCase zhUserCase = zhUserCaseMapper.selectLoading(caseId,deptId);
        //空指针异常
        if(zhUserCase != null){
            BasisTaskPlanning basisTaskPlanning =  basisTaskPlanningMapper.selectUIDAndCaseId(zhUserCase.getCaseId(),zhUserCase.getUserId());
            return R.ok(basisTaskPlanning);
        }else{
            return null;
        }

    }



    private static  double splitToNumber(String input) {
        // 匹配字母
        Pattern letterPattern = Pattern.compile("[a-zA-Z]");
        Matcher letterMatcher = letterPattern.matcher(input);
        StringBuilder letters = new StringBuilder();
        while (letterMatcher.find()) {
            letters.append(letterMatcher.group());
        }

        // 匹配数字
        Pattern numberPattern = Pattern.compile("[0-9]");
        Matcher numberMatcher = numberPattern.matcher(input);
        StringBuilder numbers = new StringBuilder();
        while (numberMatcher.find()) {
            numbers.append(numberMatcher.group());
        }
        System.out.println("Letters: " + letters);  // 输出: k
        System.out.println("Numbers: " + numbers);
        return Double.parseDouble(String.valueOf(numbers));
    }



    private static String splitToString(String input) {
        // 匹配字母
        Pattern letterPattern = Pattern.compile("[a-zA-Z]");
        Matcher letterMatcher = letterPattern.matcher(input);
        StringBuilder letters = new StringBuilder();
        while (letterMatcher.find()) {
            letters.append(letterMatcher.group());
        }
        // 匹配数字
        Pattern numberPattern = Pattern.compile("[0-9]");
        Matcher numberMatcher = numberPattern.matcher(input);
        StringBuilder numbers = new StringBuilder();
        while (numberMatcher.find()) {
            numbers.append(numberMatcher.group());
        }
        System.out.println("Letters: " + letters);  // 输出: k
        System.out.println("Numbers: " + numbers);
        return letters.toString();
    }





    public static String  upCase(String input) {
        String[] cases = generateBothCases(input);
        return cases[0];
    }






    public static String[] generateBothCases(String str) {
        return new String[] {
                str.toUpperCase(),
                str.toLowerCase()
        };
    }




//    public static void main(String[] args) {
//        System.out.println(splitToNumber("24K"));
//    }


}
